package com.backapp.app;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import com.dropbox.client2.*;
import com.dropbox.client2.DropboxAPI.UploadRequest;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.exception.DropboxException;

import android.os.AsyncTask;

/*
 * Implements the AsyncTask methods so that long running file upload task can 
 * run in the background/non-UI thread. I used to do this using Handler's in 
 * older SDKs. Kids these days..
 */
public class UploadFile extends AsyncTask<Void, Void, Boolean>
{
	private String mFileName;
	private Long mFileLength;
	private File mFileHandle;
	
	private DropboxAPI<AndroidAuthSession> mDBApi;
	private UploadRequest mRequest;
	
	private UploadListener mListener;
	
	/** 
	 * Constructor.
	 */
	public
	UploadFile(
		String fileName,
		DropboxAPI<AndroidAuthSession> DBApi,
		UploadListener listener
		)
	{
		mFileName = fileName;
		mDBApi = DBApi;
		
		mFileHandle = new File(mFileName);
		
		if (mFileHandle.exists())
		{
			mFileLength = mFileHandle.length();
		}
		
		mListener = listener;
	}

	@Override
	protected Boolean 
	doInBackground(
		Void... params
		)
	{
		boolean success = true;
		FileInputStream fis = null;
		
		try
		{
			fis = new FileInputStream(mFileHandle);
			
			mRequest = mDBApi.putFileOverwriteRequest(
				"/backapp/appdata/" + mFileHandle.getName(), 
				fis, 
				mFileLength, 
				null
				);
			
			mRequest.upload();
			
			// mDBApi.putFile(mFileName, fis, mFileLength, null, null);
		} 
		catch (DropboxException e)
		{
			success = false;
			e.printStackTrace();
		} catch (FileNotFoundException e)
		{
			success = false;
			e.printStackTrace();
		}

		return success;
	}
	
	@Override
	protected void 
	onPostExecute(
		Boolean result
		)
	{
		super.onPostExecute(result);
		Utils.logInfo("UploadFile::Post Execute");
		mListener.onUploadCompleted();
	}
}
